var salt = sessionStorage.getItem('usersalt');

layui.use(['form', 'layer'], function() {
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery;

	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);
	}

	//获取危险源类型
	$.ajax({
		url: url + 'dangerList/getAllType',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			Token: salt
		},
		success: function(data) {
			$('#type').empty();
			console.log(data);
			if(data.code == 0) {
				var list = data.data;
				var opt = '<option value="0">请选择</option>'
				for(var i = 0; i < list.length; i++) {
					opt += '<option value="' + list[i].id + '" >' + list[i].name + '</option>'
				}
				$('#type').append(opt);
				form.render();
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
});

var itemArr = [{
	isShow: 1,
	seat: "",
	factor: "常温",
	staff: "",
	task: "常规",
	shape: "固体",
	remarks: "",
}];

function initItemShow() {
	console.log(itemArr);
	var tbodyHtml = "";
	var rightTab = 1; //右侧添加按钮行数
	for(var i = 0; i < itemArr.length; i++) {
		if(itemArr[i].isShow == 1) {
			var contentHtml = ""; //检查项目内容html
			//内容框list
			/*-------------start-------------*/
			contentHtml +=
				"<tr>" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">环境影响因素</label></div>" +
				"</td>" +
				"<td>" +
				"<select id=\"item-select-factor-" + i + "-2\" onchange=\"setItemValue('item-select-factor-" + i + "-2'," + i + ",1)\" class='layui-input layui-unselect' lay-ignore>" +
				"<option value=\"原油\">原油</option>" +
				"<option value=\"含油污水\">含油污水</option>" +
				"<option value=\"非甲烷总烃\">非甲烷总烃</option>" +
				"<option value=\"废旧零配件\">废旧零配件</option>" +
				"<option value=\"排烟\">排烟</option>" +
				"<option value=\"油液\">油液</option>" +
				"<option value=\"废旧盘根\">废旧盘根</option>" +
				"<option value=\"废旧零配件\">废旧零配件</option>" +
				"<option value=\"废旧机油\">废旧机油</option>" +
				"<option value=\"废旧线缆\">废旧线缆</option>" +
				"<option value=\"废旧元件\">废旧元件</option>" +
				"<option value=\"废旧垫子/螺栓等\">废旧垫子/螺栓等</option>" +
				"<option value=\"废旧管材\">废旧管材</option>" +
				"<option value=\"工业垃圾\">工业垃圾</option>" +
				"<option value=\"沾油垃圾\">沾油垃圾</option>" +
				"<option value=\"生活垃圾\">生活垃圾</option>" +
				"<option value=\"生活污水\">生活污水</option>" +
				"</select>" +
				"</td>" +

				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">形态类别</label></div>" +
				"</td>" +
				"<td>" +
				"<select id=\"item-select-shape-" + i + "-2\" onchange=\"setItemValue('item-select-shape-" + i + "-2'," + i + ",2)\" class='layui-input layui-unselect' lay-ignore>" +
				"<option value=\"固体\">固体</option>" +
				"<option value=\"液体\">液体</option>" +
				"<option value=\"气体\">气体</option>" +
				"<option value=\"混合\">混合</option>" +
				"</select>" +
				"</td>" +

				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">作业类别</label></div>" +
				"</td>" +
				"<td>" +
				"<select id=\"item-select-task-" + i + "-2\" onchange=\"setItemValue('item-select-task-" + i + "-2'," + i + ",3)\" class='layui-input layui-unselect' lay-ignore>" +
				"<option value=\"常规\">常规</option>" +
				"<option value=\"临时\">临时</option>" +
				"</select>" +
				"</td>" +
				"<tr>" +
				"<tr>" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">涉及作业人员</label></div>" +
				"</td>" +
				"<td>" +
				"<input type=\"text\" class=\"layui-input\" id=\"item-staff-" + i + "-textarea-1\"" +
				"onchange=\"setItemValue('item-staff-" + i + "-textarea-1', " + i + ",4)\"  value=\"" + itemArr[i].staff + "\" />" +
				"</td>" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">备注</label></div>" +
				"</td>" +
				"<td>" +
				"<input type=\"text\" class=\"layui-input\" id=\"item-remarks-" + i + "-textarea-1\"" +
				"onchange=\"setItemValue('item-remarks-" + i + "-textarea-1', " + i + ",5)\"  value=\"" + itemArr[i].remarks + "\" />" +
				"</td>" +

				"</tr>";
			/*-------------end-------------*/
			//按钮合并行数+1
			++rightTab;
			tbodyHtml += contentHtml;
			/*-------------检查项目.end-------------*/
		}
	}
	$("#elementTable").html(tbodyHtml);

	for(var i = 0; i < itemArr.length; i++) {
		set_select_checked("item-select-factor-" + i + "-2", itemArr[i].factor);
		set_select_checked("item-select-shape-" + i + "-2", itemArr[i].shape);
		set_select_checked("item-select-task-" + i + "-2", itemArr[i].task);
	}

	setPosition();
}

function set_select_checked(selectId, checkValue) {
	var obj = document.getElementById(selectId).options;
	for(i = 0; i < obj.length; i++) {
		if(obj[i].value == checkValue)
			obj[i].selected = true;
	}
}
//获取显示的危险介质数量-----start
function getShowItemNum() {
	var showNum = 0;
	for(var i = 0; i < itemArr.length; i++) {
		if(itemArr[i].isShow == 1) {
			++showNum;
		}
	}
	return showNum;
}

//增加危险介质项目
function addItem() {
	var showNum = getShowItemNum();
	itemArr[showNum] = {
		isShow: 1,
		seat: "",
		factor: "常温",
		staff: "",
		task: "常规",
		shape: "固体",
		remarks: "",
	};
	initItemShow();
}

//删除危险介质项目
function delItem(index) {
	var showNum = getShowItemNum();
	if(showNum == 1) {
		return;
	}
	for(var i = 0; i < itemArr.length; i++) {
		var maxIndex = itemArr.length - 1;
		if(i >= index && i < maxIndex) {
			itemArr[i] = itemArr[i + 1];
		}
	}
	itemArr.pop();
	initItemShow();
}
//内容赋值
function setItemValue(id, itemOrder, index) {
	if(index == 1) {
		itemArr[itemOrder].factor = $("#" + id + " option:selected").val();
	} else if(index == 2) {
		itemArr[itemOrder].shape = $("#" + id + " option:selected").val();
	} else if(index == 3) {
		itemArr[itemOrder].task = $("#" + id + " option:selected").val();
	} else if(index == 4) {
		itemArr[itemOrder].staff = $("#" + id).val();
	} else if(index == 5) {
		itemArr[itemOrder].remarks = $("#" + id).val();
	}
	console.log(itemArr);
}
//新增提交
function addinfo() {
	seat = $.trim($("#seat").val()); //名称
	if(seat == "") {
		layer.msg('请填危险源位置');
		return;
	}
	var applyUnitId = getTreeVal().toString(); //适用单位id
	if(applyUnitId == 0 || applyUnitId == "") {
		if(checkId != false) { //编辑
			applyUnitId = editCompanyId;
		} else {
			layer.msg('请选择单位');
			return;
		}
	}
	var seat = $("#seat").val();
	var itemBool = judgeItemArr();
	if(!itemBool) {
		layer.msg('请填写完整项目');
		return;
	}
	if(checkId == false) { //新增时
		checkId = "";
	}

	if($('#id').val() == '') {
		postUrl = url + 'dangerList/addElement'
	} else {
		postUrl = url + 'dangerList/editElement'
	}
	
	console.log(itemArr);

	$.ajax({
		url: postUrl,
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			id: $('#id').val(),
			Token: salt,
			seat: seat,
			entId: applyUnitId,
			element: JSON.stringify(itemArr)
		},
		success: function(data) {
			if(data.code == 0) {
				var str = "新增危险源清单提交成功！";
				if(checkId != "") {
					str = "修改危险源清单提交成功！";
				}
				layer.confirm(str, {
					btn: ['确定'] //按钮
				}, function(index) {
					layer.close(index);
					location.href = "../list/list.html";
				});
			} else {
				layer.msg(data.msg);
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}

function judgeItemArr() {
	for(var i = 0; i < itemArr.length; i++) {
		if(itemArr[i].isShow == 1) {
			var factor = itemArr[i].factor;
			if(factor == "") {
				return false;
			}
		}
	}
	return true;
}

function getAllCompany() {
	$.ajax({
		url: url + 'baseEnt/getAllEnt',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {},
		success: function(data) {
			$('#applyUnitTree').empty();
			if(data.code == 0) {
				company = data.data;
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}

/*------------单位节点树.start------------*/
function showUnitTree() {
	$('#applyUnitTree').show();
}

var company;
var arr = new Array();

getAllCompany();

var setting = {
	data: {
		simpleData: {
			enable: true
		}
	},
	check: {
		enable: true,
		chkStyle: "radio", //单选框
		radioType: "all" //对所有节点设置单选
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

$.fn.zTree.init($("#applyUnitTree"), setting, company);

function zTreeOnCheck(event, treeId, treeNode) {
	var checked = treeNode.checked;
	if(checked) {
		$('#applyUnit').val(treeNode.name);
	} else {
		$('#applyUnit').val("");
	}
	$('#applyUnitTree').hide();
};

function getTreeVal() {
	var unitTreeVal = [];
	var treeObj = $.fn.zTree.getZTreeObj("applyUnitTree");
	var nodes = treeObj.getCheckedNodes(true);
	for(var i = 0; i < nodes.length; i++) {
		unitTreeVal.push(nodes[i].id); //获取选中节点的值
	}
	return unitTreeVal;
}
/*------------单位节点树.end------------*/

/*-------------元素位置.start-------------*/
function setPosition() {
	var textareaHeight = $("textarea").height();
	$(".ctddel").height(textareaHeight + 2); //2为textarea线的高度
	$(".ctdadd").height(textareaHeight + 2);
	$(".cti-add").css("margin-top", textareaHeight - 16);
}
/*-------------元素位置.end-------------*/

/*-------------编辑获取值.start-------------*/
var checkId = getQueryVariable("id");
var editCompanyId;
if(checkId != false) {
	$("#pageTitle").html("编辑危险源清单");

	$.ajax({
		url: url + 'dangerList/getInfo',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			Token: salt,
			id: checkId,
			type: 2
		},
		success: function(data) {
			if(data.code == 0) {
				initEditItem(data.data);
			} else {
				setTimeout(function() {
					layer.msg(data.msg);
				}, 1000);
				checkId = false;
				initItemShow();
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
} else {
	$("#pageTitle").html("新增危险源清单");
	//新增初始化
	initItemShow();
}

function initEditItem(checkInfo) {
	$('#id').val(checkId);
	$('#seat').val(checkInfo.seat);

	$("#applyUnit").val(checkInfo.entName);
	itemArr = JSON.parse(checkInfo.risk);
	console.log(itemArr);
	initItemShow();
	editCompanyId = checkInfo.entId;
}
/*-------------编辑获取值.end-------------*/